<template>
    <div>
        <div class="page-content-text">
            <HeaderLayout :title="$t('xxxxxxxxxx')" />

            <div class="page-content-normal">
                <div v-if="isShowEsimTips">
                    <el-alert :title="getEsimWarning" type="warning" show-icon :closable="false" />
                </div>
                <div class="flex-row" id="mobileConnection">
                    <div class="bold" style="font-size: 16px">{{ $t('xxxxx') }}</div>
                    <div>
                        
                        <el-switch id="mobileConnectionSwitch" :value="mobileConnectionValue" @change="changeMobileConnectionStatus" :disabled="getMobileConnectDisabled || mobileConnectionDisabled" v-preventReClick="1000" />
                    </div>
                </div>

                <hr />
                <div class="flex-row">
                    <div>{{ $t('1111') }}</div>
                    <div class="bold" id="signalStrength" v-show="networkModeForm.signalTextShow">{{ $t('xxxxx') }}</div>
                    <img id="signalStrength" v-show="!networkModeForm.signalTextShow" :src="networkModeForm.signalImg" class="signalImg" />
                </div>

                <div class="flex-row">
                    <div class="contentTitle_edit" id="date">{{ $t('1111') }}</div>
                    <div class="bold" id="dateValue">{{ networkModeForm.dateValue }}</div>
                </div>

                <div class="flex-row">
                    <div class="contentTitle_edit" id="currentTime">{{ $t('n') }}</div>
                    <div class="bold" id="currentTimeValue">{{ networkModeForm.currentTimeValue }}</div>
                </div>

                <div class="flex-row">
                    <div class="contentTitle_edit" id="connectionTime">{{ $t('ne') }}</div>
                    <div class="bold" id="connectionTimeValue">{{ networkModeForm.timeValue}}</div>
                </div>

                <div class="flex-row" v-if="isphoneNumberShow">
                    <div class="contentTitle_edit" id="phoneNumber">{{ $t('net') }}</div>
                    <div class="bold" id="phoneNumberValue">{{ networkModeForm.phoneNumber }}</div>
                </div>

                <div>
                    <div v-if="!isMultiApn">
                        <div class="flex-row-break">
                            <div class="contentTitle_edit" id="ipAddress">{{ $t('c') }}</div>
                            <div class="bold">
                                <div id="ipAddressValue">{{ networkModeForm.ipAddress }}</div>
                                <div id="ipAddressValue_IPV6">{{ networkModeForm.ipAddress_IPV6 }}</div>
                            </div>
                        </div>

                        <div class="flex-row-break">
                            <div class="contentTitle_edit" id="gateway">{{ $t('ne') }}</div>
                            <div class="bold">
                                <div id="gatewayValue">{{ networkModeForm.gateway }}</div>
                                <div id="gatewayValue_IPV6">{{ networkModeForm.gateway_IPV6 }}</div>
                            </div>
                        </div>

                        <div class="flex-row-break">
                            <div class="contentTitle_edit" id="primaryDnsServer">{{ $t('net') }}</div>
                            <div class="bold">
                                <div id="primaryDnsServerValue">{{ networkModeForm.primaryDnsServer }}</div>
                                <div id="primaryDnsServerValue_IPV6">{{ networkModeForm.primaryDnsServer_IPV6 }}</div>
                            </div>
                        </div>

                        <div class="flex-row-break">
                            <div class="contentTitle_edit" id="secondaryDnsServer">{{ $t('netW') }}</div>
                            <div class="bold">
                                <div id="secondaryDnsServerValue">{{ networkModeForm.secondaryDnsServer }}</div>
                                <div id="secondaryDnsServerValue_IPV6">{{ networkModeForm.secondaryDnsServer_IPV6 }}</div>
                            </div>
                        </div>

                        <div style="text-align: end" v-if="isShowModuleInfoPage">
                            <span id="moduleInfoBtn" class="subTitle_blue_btn" style="margin: 0" @click="jumpUrl('/netWork/mobileSetting')">{{ $t('dat') }}</span>
                        </div>
                    </div>
                    <div v-else>
                        <div class="tab-header">
                            <el-radio-group v-model="apnTabCurrent">
                                <el-radio-button :id="'APN' + (index + 1)" :label="apnItem.default" v-for="(apnItem, index) in apnList" :key="apnItem.default"
                                    >{{ apnItem.name }} <span v-if="defalutId === apnItem.default">({{ $t('netW') }})</span>
                                </el-radio-button>
                            </el-radio-group>
                        </div>
                        <el-table id="apnTable" :header-row-style="{ background: 'rgba(3,0,0,0.1)' }" class="center-table" stripe :data="formatCurrentApnList" border>
                            <el-table-column :resizable="false" prop="name">
                                <template #header>
                                    <span>APN{{ apnTabCurrent }}</span>
                                </template>
                                <template slot-scope="scope">
                                    <span :id="'nameValue_' + scope.$index" style="word-break: keep-all">{{ scope.row.name }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column :resizable="false" prop="ipv4" label="IPv4">
                                <template slot-scope="scope">
                                    <span :id="'ipv4Value_' + scope.$index">{{ scope.row.ipv4 }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column :resizable="false" prop="ipv6" label="IPv6">
                                <template slot-scope="scope">
                                    <span :id="'ipv6Value_' + scope.$index">{{ scope.row.ipv6 }}</span>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </div>   
            
             <!-- esim 配置 -->
            <template v-if="esim.show">
                <div id="currentSim" class="page-content-normal" v-if="!HUMAX">
                    <hr />
                    <div class="flex-row">
                        <div>
                            <div class="contentTitle_edit">{{ $t('net') }}</div>
                            <div id="currentSim" class="contentValue_16B"> sim {{ esim.currentSim + 1}}</div>
                        </div>
                    </div>
                </div>
                <template v-if="!esim.esimEdit">
                    <div id="currentSim" class="page-content-normal">
                        <hr />
                        <div class="flex-row">
                            <div>
                                <div class="contentTitle_edit">{{ $t('netWolection') }}</div>
                                <div id="simSelection" class="contentValue_16B">{{ formEsim(esim.esimValue) }}</div>
                            </div>
                            <div>
                                <span class="fr-edit" id="simSelectionEditBtn" @click="editEsim">{{ $t('coutton') }}</span>
                            </div>
                        </div>
                    </div>
                </template>

                <template v-else>
                    <div class="page-content-normal">
                        <hr />
                    </div>
                    <div class="page-content-edit">
                        <el-form label-position="top">
                            <el-form-item :label="$t('netion')">
                                <el-select id="networkMode_edit" v-model="esim.esimValue" placeholder="">
                                    <div id="networkMode_select">
                                        <el-option v-for="item in esim.esimOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                                    </div>
                                </el-select>
                            </el-form-item>

                            <div style="height: 10px; line-height: 10px"></div>
                            <el-form-item>
                                <el-button :loading="esim.esimBtnLoading" id="saveButton" type="primary" round @click="setEsim">{{ $t('coutton') }}</el-button>
                                <el-button :loading="esim.esimBtnLoading" id="cancelButton" type="info" @click="cancelEsim">{{ $t('coelButton') }}</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </template>

                <template v-if="networkModeForm.edit">
                    <div class="page-content-normal">
                        <hr />
                    </div>
                </template>
            </template>

            <!-- 设置network mode -->
            <div id="networkMode">
                <div v-if="!networkModeForm.edit" class="page-content-normal">
                    <hr />
                    <div class="flex-row">
                        <div>
                            <div class="contentTitle_edit">{{ $t('netvanceLabel5') }}</div>
                            <div id="networkMode" class="contentValue_16B">{{ networkModeForm.value | formNetMode }}</div>
                        </div>
                        <div>
                            <span v-if="mobileSetting.edit" id="networkModeEditBtn" class="fr-edit" @click="changeNetworkModeStatus">{{ $t('common.editButton') }}</span>
                            <span v-else class="fr-edit-disabled">{{ $t('common.editButton') }}</span>
                        </div>
                    </div>
                </div>

                <div v-if="networkModeForm.edit" class="page-content-edit">
                    <el-form ref="networkModeForm" :model="networkModeForm">
                        <div class="contentTitle_edit">{{ $t('neanceLabel5') }}</div>
                        <el-form-item>
                            <el-select id="networkMode_edit" v-model="networkModeForm.value" placeholder="">
                                <div id="networkMode_select">
                                    <el-option v-for="item in networkModeForm.options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                                </div>
                            </el-select>
                        </el-form-item>

                        <div style="height: 10px; line-height: 10px"></div>
                        <el-form-item>
                            <el-button id="saveButton" type="primary" round @click="onNetworkModeSubmit">{{ $t('common.saveButton') }}</el-button>
                            <el-button id="cancelButton" type="info" @click="onNetworkModeCancle">{{ $t('common.cancelButton') }}</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
            <!-- APN设置 -->
            <div id="APNSettings">
                <div class="page-content-normal">
                    <hr />
                    <div class="flex-row">
                        <div>
                            <div class="contentTitle_edit">{{ $t('neingTitle') }}</div>
                            <div id="apnSettingsValue" class="contentValue_16B">{{ apnSettingsForm.value }}</div>
                        </div>
                        <div>
                            <!-- apnSettingsForm.edit -->
                            <span v-if="true" id="apnSettingsEditBtn" class="fr-edit" @click="jumpAPNUrl">{{ $t('cButton') }}</span>
                            <span v-else class="fr-edit-disabled">{{ $t('cotton') }}</span>
                        </div>
                    </div>
                    <hr style="margin-top: 16px" />
                </div>
            </div>

            <div class="page-content-normal" id="dataRoaming">
                <div class="flex-row" id="mobileConnection">
                    <div class="bold" style="font-size: 16px">{{ $t('neext') }}</div>
                    <div>
                        <el-switch id="openDataRoamingSwitch" v-model="dataRoamingValue" @change="openDataRoamingDialog" :disabled="dataRoamingDisabled" />
                    </div>
                </div>
            </div>

            <div style="margin-top: 30px">
                <div v-if="isSimSecurityPageShow">
                    <span id="simSecurityBtn" class="subTitle_blue_btn" @click="jumpUrl('/netWork/mobileSettings/simSecurity')">{{ $t('neturityPage') }}</span>
                </div>
                <div v-if="isManualNetworkSearchShow">
                    <span id="manualNetworkSearchBtn" class="subTitle_blue_btn" @click="jumpUrl('/netWork/mobileSettings/manualNetworkSearch')">{{ $t('netalNetworkSearch') }}</span>
                </div>

                <div v-if="HUMAX">
                    <span id="manualNetworkSearchBtn" class="subTitle_blue_btn" @click="jumpUrl('/netWork/mobileSettings/cellLock')">{{ $t('netWle') }}</span>
                </div>

                <div v-if="isShowBandSettingPage">
                    <span id="bandSettingBtn" class="subTitle_blue_btn" @click="jumpUrl('/netWork/mobileSettings/bandSetting')">{{ $t('bandSe') }}</span>
                </div>

                <div v-if="isShowEsimProfileManagement">
                    <el-link type="primary" :disabled="!getEsimEntry" :underline="false" id="esimProfileManagement" class="subTitle_blue_btn" @click="jumpUrl('/netWork/mobileSettings/esimList')">{{ $t('netWork.mobileSettings.esim.eSimProfileManagement') }}</el-link>
                </div>
            </div>

            <div style="height: 30px; line-height: 30px"></div>
        </div>

        <confirm-dialog :btnLoading="dRmBtnLoading" ref="roamingRef" id="confirmDialog" :title="$t('netWgLabel1')" :confirm-text="$t('comton')" @confirm="onDataRoamingSubmit" @cancel="onCancle">
            <span>{{ $t('netWork.mobngLabel2') }}</span>
        </confirm-dialog>

        <confirm-dialog id="ipptTips" ref="ipptTipsRef" @confirm="jumpUrl('/netng')" @cancel="mobileConnectionValue = false" :confirmText="$t('coodify')">
            <span>{{ $t('neogInfo') }}</span>
        </confirm-dialog>

        <RoamTips :btnLoading="dRmBtnLoading" ref="RoamTips" :polling="false" isConfirm @confirm="onDataRoamingSubmit" />
    </div>
</template>

<script>
import { cloneDeep, update } from 'lodash-es';

import i18n from '@/lang';
import { accordingToEv } from '@/utils/common';
import useRoam from '@/hooks/useRoam';
import RoamTips from '@/components/common/RoamTips/index.vue';
import { LOCAL_KEY } from '@/constant/dict';
import {getInternetInfo,setInternetInfo,getSimSlot,getProfileInfo} from '@/api/mobile';

// 信号图标对象集 -- MobileSetting
const signalIcon = {
    0: require('@/assets/images/network_img_signal_0@3.png'),
    1: require('@/assets/images/network_img_signal_1@3.png'),
    2: require('@/assets/images/network_img_signal_2@3.png'),
    3: require('@/assets/images/network_img_signal_3@3.png'),
    4: require('@/assets/images/network_img_signal_4@3.png')
};

export default {
    mixins: [useRoam],
    components: { RoamTips },
    data() {
        return {
            mobileInfo: {
                internet:{},
                sim:{},
                network_search:{}
            },
            simStatus: '',
            timer: null,
            refreshTimer: null,
            mobileConnectionValue: false,
            mobileConnectionDisabled: false,
            tableData: [],
            mobileConnectionData: [],
            networkModeForm: {
                simStatus: 'No SIM',
                signalImg: signalIcon[4],
                signalTextShow: true,
                edit: false,
                dateValue: '',
                currentTimeValue: '',
                timeValue: '',
                ipAddress: '',
                ipAddress_IPV6: '',
                gateway: '',
                gateway_IPV6: '',
                primaryDnsServer: '',
                primaryDnsServer_IPV6: '',
                secondaryDnsServer: '',
                secondaryDnsServer_IPV6: '',
                phoneNumber: '',
                options: [
                     {
                        value: '2G',
                        label: '2G'
                    },
                     {
                        value: '3G',
                        label: '3G'
                    },
                    {
                        value: '4G',
                        label: '4G'
                    },
                    {
                        value: '5G',
                        label: '5G'
                    },
                    {
                        value: 'AUTO',
                        label: this.$t('netWork.wifiSettings.item_wifi_auto_ch_2g_0')
                    }
                ],
                value: ''
            },
            apnSettingsForm: {
                edit: true,
                value: this.$t('netWork.apnSettings.Default')
            },
            mobileSetting: {
                edit: true
            },
            dataRoamingValue: false,
            NATValue: false,
            dataRoamingDisabled: false,
            isphoneNumberShow: false,
            isSimSecurityPageShow: false,
            apnTabCurrent: '1',
            defalutId: '1',
            apnList: [
                {
                    default: '1',
                    name: 'APN1',
                    ip4: '',
                    ip6: '',
                    gateway4: '',
                    gateway6: '',
                    primary4: '',
                    primary6: '',
                    secondary4: '',
                    secondary6: ''
                },
                {
                    default: '2',
                    name: 'APN2',
                    ip4: '',
                    ip6: '',
                    gateway4: '',
                    gateway6: '',
                    primary4: '',
                    primary6: '',
                    secondary4: '',
                    secondary6: ''
                },
                {
                    default: '3',
                    name: 'APN3',
                    ip4: '',
                    ip6: '',
                    gateway4: '',
                    gateway6: '',
                    primary4: '',
                    primary6: '',
                    secondary4: '',
                    secondary6: ''
                },
                {
                    default: '4',
                    name: 'APN4',
                    ip4: '',
                    ip6: '',
                    gateway4: '',
                    gateway6: '',
                    primary4: '',
                    primary6: '',
                    secondary4: '',
                    secondary6: ''
                }
            ],
            formatCurrentApnList: [
                {
                    name: this.$t('common.IP_Label'),
                    ipv4: '',
                    ipv6: '',
                    default: this.$t('netWork.apnSettings.Default')
                },
                {
                    name: this.$t('netWork.wanSettings.gatewayTitle'),
                    ipv4: '',
                    ipv6: '',
                    default: this.$t('netWork.apnSettings.Default')
                },
                {
                    name: this.$t('netWork.mobileSettings.primaryDnsTitle'),
                    ipv4: '',
                    ipv6: '',
                    default: this.$t('netWork.apnSettings.Default')
                },
                {
                    name: this.$t('netWork.mobileSettings.secondaryDnsTitle'),
                    ipv4: '',
                    ipv6: '',
                    default: this.$t('netWork.apnSettings.Default')
                }
            ],
            tr069Ipv4AndIpv6Status: false,
            img_t: '?_t=' + new Date().getTime().toString(),
            switchLoading: false,
            esim: {
                show: false,
                esimEdit: false,
                currentSim: void 0,
                esimValue: void 0,
                esimValueClone: void 0,
                esimOptions: [
                    {
                        value: '0',
                        label: this.$t('netWork.wifiSettings.item_wifi_auto_ch_2g_0')
                    },
                    {
                        value: '1',
                        label: 'USIM'
                    },
                    {
                        value: '2',
                        label: 'ESIM'
                    }
                ],
                esimBtnLoading: false
            },
            dRmBtnLoading: false,
            HUMAX: false,
            flag: true,
        };
    },
    created() {
        this.add3G();

        // if (this.isMultiApn) {
        //     this.getApnDefaultAndList();
        // }

        this.onLoad_mobileConnection();
        this.onLoad();
        this.updateCurrentTime();
        this.isShowEsim();
        this.fetchEsim();
        // 082/091去掉 esim auto
        if (this.HUMAX) {
            this.esim.esimOptions.shift();
        }
    },
    computed: {
        isMultiApn() {
            return this.HUMAX;
        },
        isManualNetworkSearchShow() {
            return false;
        },

        isShowModuleInfoPage() {
            return false;
        },

        isShowBandSettingPage() {
            return false;
        },

        isShowEsimProfileManagement() {
            return false;
        },

        getMobileConnectDisabled() {
            console.log("mobileInfo:",this.mobileInfo.internet.ezmesh_role)
            const isAgent = this.mobileInfo.ezmesh_role === 'agent';
            console.log("isAgent:",isAgent)

            const isNoSim = this.networkModeForm.simStatus === 'No SIM';
            const result = this.tr069Ipv4AndIpv6Status || isAgent || isNoSim || false;
            console.log("result:",result)
            return result;
        },

        isShowEsimTips() {
            return this.esim.show && ['3', '4', '5'].includes(this.esim.currentSim);
        },

        getEsimWarning() {
            return ['3', '4'].includes(this.esim.currentSim) ? this.$t('netWork.mobileSettings.esim.businessNumberErrorTips') : this.formatEsimStatus(this.esim.currentSim);
        },

        getEsimEntry() {
            return this.formatEsimStatus(this.esim.currentSim) && this.formatEsimStatus(this.esim.currentSim).includes('ESIM');
        }
    },
    mounted() {
        this.startTimer();
        this.startRefresh();
    },
    beforeDestroy() {
        if (this.timer && this.timer != null) {
            clearInterval(this.timer);
        }

        if (this.refreshTimer && this.refreshTimer != null) {
            clearInterval(this.refreshTimer);
        }
    },
    watch: {
        apnTabCurrent(newVal, oldVal) {
            if (newVal != oldVal) {
                this.formatCurrentApnData(newVal);
            }
        },
        simStatus(newVal) {
            if (!['connected', 'connecting'].includes(newVal)) {
                this.formatCurrentApnList.forEach((item) => {
                    item.ipv4 = '--';
                    item.ipv6 = '--';
                });
            } else {
                this.formatCurrentApnData(this.defalutId);
            }
        }
    },
    methods: {
        formatCurrentApnData(currentVal) {
            const currentApn = this.apnList.find((item) => item.default === currentVal);
            if (currentApn) {
                const values = [currentApn.ip4, currentApn.ip6, currentApn.gateway4, currentApn.gateway6, currentApn.primary4, currentApn.primary6, currentApn.secondary4, currentApn.secondary6];
                this.formatCurrentApnList.map((item, index) => {
                    item.ipv4 = values[index * 2] || '--';
                    item.ipv6 = values[index * 2 + 1] || '--';
                });
                if (currentApn.default === this.defalutId) {
                    this.formatCurrentApnList.forEach((element) => {
                        element.default = this.$t('netWork.apnSettings.Default');
                    });
                } else {
                    this.formatCurrentApnList.forEach((element) => {
                        element.default = '--';
                    });
                }
            }
        },
        startTimer() {
            this.timer = setInterval(() => {
                this.updateCurrentTime();
            }, 1000);
        },
        startRefresh() {
            // 使用setInterval等之类的定时器时，要考虑定时器叠加问题
            if (this.refreshTimer) {
                clearInterval(this.refreshTimer);
            }
            this.refreshTimer = setInterval(() => {
                this.onLoad();
                // if (this.isMultiApn) {
                //     this.getApnDefaultAndList();
                // }
                this.isShowEsim();
            }, 10000);
        },
        async onLoad_mobileConnection() {
            
            const res_mobileConnection = await getInternetInfo().catch((err) => {
                console.log(err);
            });
            //success
            if (res_mobileConnection.internet.select_mode == 'manual_select') {
                this.mobileConnectionValue = false;
            } else {
                this.mobileConnectionValue = true;
            }

            // 恢复 switch 请求发起
            this.switchLoading = false;
        },
        async onLoad() {
           
         
            let res= await getInternetInfo();
            console.log("res internet:",res.internet)
            this.mobileInfo.internet = res.internet;
            console.log("mobileInfo1:",this.mobileInfo)
            this.mobileInfo.network_search = res.network_search;
            this.mobileInfo.sim = res.sim;
            console.log("mobileInfo2:",this.mobileInfo)

            const isIPv4Enabled = res.internet.ipAddress ? true:false
            
            const isIPv6Enabled = res.internet.ipAddress_IPV6 ? true:false;
            console.log("isIPv6Enabled:",isIPv6Enabled)

            this.tr069Ipv4AndIpv6Status = !isIPv4Enabled && !isIPv6Enabled;

            //success
            let ezmeshRole = res.internet.ezmesh_role;
            if (ezmeshRole == 'Agent') {
                this.dataRoamingDisabled = true;
                this.mobileSetting.edit = false;
                this.apnSettingsForm.edit = false;

                this.isManualNetworkSearchShow = false;
                this.isSimSecurityPageShow = false;
            }

           
          
            let usim = res.sim.sim_status
            if (usim == '' || usim == '无线装置已关闭' || usim == '不在服务区' || usim == '已断开连接'|| usim == '未知'|| usim == 'Radio Off' || usim == 'Out of Service' || usim == 'Disconnected'|| usim == 'Unknown') {
                this.networkModeForm.simStatus = 'No SIM';
            } else if (usim == '已连接' || usim == '正在连接'|| usim == '服务中'||usim == 'Connected' || usim == 'Connecting'|| usim == 'In Service') {
                this.networkModeForm.simStatus = 'service';
            } else {
                this.networkModeForm.simStatus = 'SIM ready';
            }
            let signalStrength = res.sim.signal_strength;

            if (this.networkModeForm.simStatus == 'service') {
                this.networkModeForm.signalTextShow = false;
                this.networkModeForm.signalText = signalStrength;
                this.networkModeForm.signalImg = signalIcon[this.setSignalNum(signalStrength)];
            } else {
                this.networkModeForm.signalTextShow = true;
            }

            //Connection Time
            this.networkModeForm.timeValue = res.network_search.connected_time;

            if (this.networkModeForm.signalTextShow) {
                //IP Address
                this.networkModeForm.ipAddress = 'IPv4: --';
                this.networkModeForm.ipAddress_IPV6 = 'IPv6: --';
                //Gateway
                this.networkModeForm.gateway = 'IPv4: --';
                this.networkModeForm.gateway_IPV6 = 'IPv6: --';
                //Primary DNS Server
                this.networkModeForm.primaryDnsServer = 'IPv4: --';
                this.networkModeForm.primaryDnsServer_IPV6 = 'IPv6: --';
                //Secondary DNS Server
                this.networkModeForm.secondaryDnsServer = 'IPv4: --';
                this.networkModeForm.secondaryDnsServer_IPV6 = 'IPv6: --';
            } else {
                //IP Address
                let tmpval;
                tmpval = res.internet.ipAddress;
                if (tmpval != '') {
                    this.networkModeForm.ipAddress = 'IPv4: ' + tmpval;
                    console.log("ipAddress:",this.networkModeForm.ipAddress)
                }
                tmpval = res.internet.ipAddress_IPV6;
                if (tmpval != '') {
                    this.networkModeForm.ipAddress_IPV6 = 'IPv6: ' + tmpval;
                }

                //Gateway
                tmpval = res.internet.gateway;
                if (tmpval != '') {
                    this.networkModeForm.gateway = 'IPv4: ' + tmpval;
                }
                tmpval = res.internet.gateway_IPV6;
                if (tmpval != '') {
                    this.networkModeForm.gateway_IPV6 = 'IPv6: ' + tmpval;
                }

                //Primary DNS Server
                tmpval = res.internet.primaryDnsServer;
                if (tmpval != '') {
                    this.networkModeForm.primaryDnsServer = 'IPv4: ' + tmpval;
                }
                tmpval = res.internet.primaryDnsServer_IPV6;
                if (tmpval != '') {
                    this.networkModeForm.primaryDnsServer_IPV6 = 'IPv6: ' + tmpval;
                }

                //Secondary DNS Server
                tmpval = res.internet.secondaryDnsServer;
                this.networkModeForm.secondaryDnsServer = '';
                if (tmpval != '') {
                    this.networkModeForm.secondaryDnsServer = 'IPv4: ' + tmpval;
                }
                tmpval = res.internet.secondaryDnsServer_IPV6;
                if (tmpval != '') {
                    this.networkModeForm.secondaryDnsServer_IPV6 = 'IPv6: ' + tmpval;
                }
            }

            //Phone Number
            this.networkModeForm.phoneNumber = res.sim.local_phone_number.replace('"', '').replace('"', '');
            if (this.networkModeForm.phoneNumber != 'NULL' && this.networkModeForm.phoneNumber != '--' && this.networkModeForm.phoneNumber != '') {
                this.isphoneNumberShow = true;
            } else {
                this.isphoneNumberShow = false;
            }

            //5G Network mode selection
            if (!this.networkModeForm.edit) {
                console.log('network_mode:', res.network_search.network_type);
                let generation;
                switch (res.network_search.network_type) {
                    case "28":
                    generation= '5G';    // 5G网络
                    break;
                    case "9":
                    generation = '4G';    // 4G网络
                    break;
                    case "0":
                    generation = '3G';    
                    break;
                    case "1":
                    generation = '2G';   
                    break;
                    case "5G":
                    generation= '5G';    // 5G网络
                    break;
                    case "4G":
                    generation = '4G';    // 4G网络
                    break;
                    case "3G":
                    generation = '3G';    
                    break;
                    case "2G":
                    generation = '2G';   
                    break;
                    default:
                    generation = '';  
                }
                this.networkModeForm.value = generation;
                
            }

            const profileInfo = await getProfileInfo();
            console.log("apn:",profileInfo);
            //APN Settings
            if (this.isMultiApn) {
                this.apnSettingsForm.value = 'APN ' + profileInfo.select_profile_id;
            } else {
                this.apnSettingsForm.value = this.$t('netWork.vpnSetting.profileTitle') + ' ' + profileInfo.select_profile_id;
            }
            if (this.networkModeForm.simStatus == 'No SIM' || ezmeshRole == 'Agent') {
                this.apnSettingsForm.edit = false;
            } else {
                this.apnSettingsForm.edit = true;
            }

            //Data Roaming
            if (res.data_roaming_enable == '0') {
                this.dataRoamingValue = false;
            } else {
                this.dataRoamingValue = true;
            }

            //NAT
            if (!res.wan_nat) {
                this.NATValue = false;
            } else {
                this.NATValue = true;
            }
        },
        // 设置信号值
        setSignalNum(value) {
             return value ? (+value > 0 ? (+value > 4 ? 4 : +value) : 0) : 0;
        },
         async pollingData() {

            this.timer = setInterval(async () => {
                  await this.onLoad();
            }, 5000);
        },
        getTimeZoneName(timezoneOffset) {
            let offset = Math.floor(Math.abs(timezoneOffset) / 60);
            let sign = timezoneOffset > 0 ? '-' : '+';

            let timezone = `UTC${sign}${offset}`;

            return timezone;
        },
        updateCurrentTime() {
            /*Foxconn KevinLiao add for get date and current time start, 2020-02-18*/
            let Today = new Date();
            let timeZoneName = this.getTimeZoneName(Today.getTimezoneOffset());
            let year = Today.getFullYear();
            let month = this.$t(`common.monthName${Today.getMonth() + 1}`);
            let date = parseInt(Today.getDate());
            if (date < 10) {
                date = '0' + date.toString();
            }
            let hours = parseInt(Today.getHours());
            if (hours < 10) {
                hours = '0' + hours.toString();
            }
            let minutes = parseInt(Today.getMinutes());
            if (minutes < 10) {
                minutes = '0' + minutes.toString();
            }
            let Seconds = parseInt(Today.getSeconds());
            if (Seconds < 10) {
                Seconds = '0' + Seconds.toString();
            }
            let week = this.$t(`common.weekName${Today.getDay()}`);

            //Date
            if (localStorage.getItem(LOCAL_KEY.IS_CURRENT_LANGUAGE) === 'fr') {
                this.networkModeForm.dateValue = week + ' ' + date + ' ' + month + ' ' + year;
            } else {
                this.networkModeForm.dateValue = month + ' ' + date + ' ' + week + ' , ' + year;
            }

            //Current Time
            this.networkModeForm.currentTimeValue = hours + ':' + minutes + ':' + Seconds + ' ' + timeZoneName;
        },

        async changeMobileConnectionStatus(value) {
            this.mobileConnectionDisabled = true;

            console.log('set select mode...')
            this.mobileConnectionValue = !this.mobileConnectionValue
            this.fetchEsim()
            const result = await this.internetInfoSet(this.esim.currentSim,"mobile_data_enable",this.mobileConnectionValue)

            // this.onCancle();
            result == 'success' ? this.$message.success(this.$t('common.success')) : this.$message.error(this.$t('common.error'));
            this.onLoad_mobileConnection();
            setTimeout(() => {
                this.mobileConnectionDisabled = false;
            }, 10000);
        },

        async openDataRoamingDialog() {
            clearInterval(this.refreshTimer);
            if (this.dataRoamingValue) {
                this.dRmBtnLoading = false;
                this.$refs.roamingRef.show();
            } else {
                // 是否需要漫游关闭提醒
                if (this.isRoamTips) {
                    // 漫游入网
                    if (this.$store.state.firmware.isRoamStatus) {
                        // 成功拨号
                        let simStatus = this.$store.state.config.simStatus

                        if (simStatus == 'connected') {
                            this.$refs.RoamTips.showDialog();
                            return;
                        }
                    }
                }

                this.onDataRoamingSubmit();
            }
        },
        async onDataRoamingSubmit() {
            this.dRmBtnLoading = true;
            this.dataRoamingDisabled = true;

            console.log('set roaming value...')
            this.fetchEsim()
            const result =await this.internetInfoSet(this.esim.currentSim,"data_roaming_enable",this.dataRoamingValue)
            if (result.$message == 'success') {
                this.onCancle();
                this.$message.success(this.$t('common.success'));
            } else {
                this.onCancle();
                this.$message.error(this.$t('common.error'));
            }
            this.startRefresh();
        },
        async onNATSubmit() {
            clearInterval(this.refreshTimer);
            this.fetchEsim()
            const result =await this.internetInfoSet(this.esim.currentSim,"nat_value",this.NATValue)

            if (result == 'success') {
                this.onCancle();
                this.$message.success(this.$t('common.success'));
            } else {
                this.onCancle();
                this.$message.error(this.$t('common.error'));
            }
        },
        onCancle() {
            if (this.isRoamTips) {
                this.$refs.RoamTips.hideDialog();
            }

            this.dataRoamingDisabled = false;
            this.mobileConnectionDisabled = false;
            this.dRmBtnLoading = false;
            this.$refs.roamingRef.hide();
            this.onLoad();
            this.onLoad_mobileConnection();
            this.startRefresh();
        },
        changeNetworkModeStatus() {
            this.networkModeForm.edit = !this.networkModeForm.edit;
        },
        jumpAPNUrl() {
            this.$router.push('/netWork/mobileSettings/apnSettings');
        },
        changeRoamingStatus() {
            this.apnSettingsForm.edit = !this.apnSettingsForm.edit;
        },
        async onNetworkModeSubmit() {
            //todo: 修改网络模式
            console.log('set network type:')
            let type;
            switch (this.networkModeForm.value) {
                                case '5G':
                                type = 28;    // 5G网络
                                break;
                                case '4G':
                                type = 9;   // 4G网络
                                break;
                                case '3G':
                                type = 0;    // 
                                break;
                                case '2G':
                                type = 1;    // 
                                break;
                                default:
                                type = -1;  
                            }
            this.fetchEsim()
            const result =await this.internetInfoSet(this.esim.currentSim,"network_type",type)
           
            if (result == 'success') {
                this.$message.success(this.$t('common.success'));
                this.networkModeForm.edit = false;
            } else {
                this.$message.error(this.$t('common.error'));
                this.onNetworkModeCancle();
            }
        },
        onNetworkModeCancle() {
            this.networkModeForm.edit = false;
            this.onLoad();
        },
        jumpUrl(_type) {
            this.$router.replace(_type);
        },

        add3G() {
            const flag = false;

            if (flag) {
                this.networkModeForm.options.unshift({
                    value: '3G',
                    label: '3G'
                });
            }
        },

        /**
         * 是否显示 Esim
         */
        isShowEsim() {
            // if (false) {
            //     this.fetchEsim();
            // }
        },

        /**
         * 获取 ESIM
         */
        async fetchEsim() {
            console.log('获取 ESIM');   
            const res = await getSimSlot(); 
            const selectValue = res.sim_select_value
            this.esim.show =  selectValue !== '-1';
            this.esim.currentSim = res.current_slot;
            this.esim.esimValueClone = cloneDeep(this.esim.esimValue);
        },
     

        /**
         * 编辑 Esim
         */
        editEsim() {
            this.esim.esimEdit = true;
            this.esim.esimBtnLoading = false;
        },

        /**
         * 取消编辑 Esim
         */
        cancelEsim() {
            this.esim.esimEdit = false;
            this.esim.esimBtnLoading = false;
            this.esim.esimValue = this.esim.esimValueClone;
        },

        /**
         * 设置 ESIM
         */
        async setEsim() {
            if (this.esimBtnLoading) {
                return;
            }

            if (this.esim.esimValueClone == this.esim.esimValue) {
                this.cancelEsim();
                return;
            }

            this.esim.esimBtnLoading = true;
           
            //todo
            this.fetchEsim()
            const result =await this.internetInfoSet(this.esim.currentSim,"sim_select_value",this.esim.esimValue)

            if (result === 'success') {
                // 开启倒计时
                this.$countDown(10, {
                    end: () => {
                        this.fetchEsim();
                        this.$message.success(this.$t('common.success'));
                    }
                });
            } else {
                this.$message.error(this.$t('common.error'));
            }
            this.cancelEsim();
        },
         async internetInfoSet(slotId,pramName, value) {
            try { 
                console.log('internetInfoSet...')
                const netConfig = {
                    slot_id:`${slotId}`,
                    [pramName]:`${value}`
                }
                console.log('set internet Info:', netConfig)
                let res = await setInternetInfo(netConfig)
                console.log('set internet Info res:', res.$message)
                return  res;  
            } catch (error) {
                console.log(error);
            }
           
         },

        /**
         * 根据返回值设置预览值
         * @param {String} str
         */
        formEsim(str) {
            const res = this.esim.esimOptions.find((option) => option.value == str);
            return res ? res.label : i18n.t('netWork.wifiSettings.item_wifi_auto_ch_2g_0');
        },

        formatEsimStatus(status) {
            const esimMap = new Map([
                ['1', "sim 2"],
                ['2', this.$t('esimStatusTips.code_2')],
                ['3', this.$t('esimStatusTips.code_3')],
                ['4', this.$t('esimStatusTips.code_4')],
                ['0', "sim 1"]
            ]);

            return esimMap.get(status);
        }
    },
    filters: {
        formNetMode(str) {
            return str == '' || str == 'AUTO' ? i18n.t('netWork.wifiSettings.item_wifi_auto_ch_2g_0') : str;
        }
    }
};
</script>
<style scoped lang="less">
@import '@/assets/css/theme_blue/component_common.less';
@import '@/assets/css/theme_blue/component_round.less';

/deep/ .el-radio-group {
    display: flex;
    overflow-x: auto;
}

/deep/ .el-radio-button .el-radio-button--medium .is-active {
    /deep/.el-radio-button__inner:hover {
        color: #fff;
    }
}
/deep/.el-radio-button__inner:hover {
    color: @radioColor;
}

/deep/.el-radio-button__orig-radio:checked + .el-radio-button__inner {
    background-color: @radioColor !important;
    border-color: @radioColor !important;
    box-shadow: -1px 0 0 0 @radioColor !important;
    &:hover {
        color: #fff;
    }
}
/deep/ .el-radio-button .el-radio-button__inner {
    border-radius: 0px;
}
/deep/ .el-radio-button__inner {
    border-bottom: none;
}

/deep/ .el-table th {
    font-size: 14px;
    background: rgba(3, 0, 0, 0.1);
    font-family: Microsoft YaHei-Regular, Microsoft YaHei;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.8);
    text-align: center;
    font-weight: 600;
}
/deep/ .el-table td {
    text-align: center;
    font-size: 14px;
    font-family: Microsoft YaHei-Regular, Microsoft YaHei;
    font-weight: 400;
    height: 80px;
}
.tab-header {
    border-bottom: 1px solid #e4e7ed;
    margin-bottom: 24px;
}

.center-table {
    margin-bottom: 30px;
}
</style>
